﻿#region license
/*****************************************
*CopyRight (c) 2009-2013 HangJing Teconology. All Rights Reserved.
*Function : 百度地图服务端类
*Created by jijunjian at 2013/12/3 11:21:32.
*E-Mail: jijunjian@ihangjing.com
*****************************************/
#endregion
using Hangjing.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace Hangjing.BaiduMapServerAPI
{
    /// <summary>
    /// 百度地图服务端类
    /// </summary>
    public class BaiduMap
    {
        string _slat, _slng, _elat, _elng;
        string cityname = "长春";

        public string bdlat = "00", bdlng;//百度坐标

        public BaiduMap(string slat, string slng, string elat, string elng, string _cityname)
        {
            _slat = slat;
            _slng = slng;
            _elat = elat;
            _elng = elng;
            cityname = _cityname;
        }

        /// <summary>
        /// 坐标转换使用
        /// </summary>
        /// <param name="lat"></param>
        /// <param name="lng"></param>
        public BaiduMap(string _lat, string _lng)
        {
            _slat = _lat;
            _slng = _lng;
        }

        /// <summary>
        /// 获取驾车距离,如果出错,返回直线距离(公里)
        /// </summary>
        /// <returns></returns>
        public decimal getDrivingDistance()
        {
            decimal distance = 0;
            /**************解析***************/
            BaiduMapInfo mapdata = accessBaiduServer();
            if (mapdata.status == "0")
            {
                string jsonstr = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(mapdata.result);
                BaiduResults rs = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<BaiduResults>(jsonstr);
                if (rs != null && rs.routes != null & rs.routes.Count > 0)
                {
                    //distance = Convert.ToDecimal(Convert.ToDouble(rs.routes[0].distance) / 1000 * (1 + 0.03));//转成公里 //客户要求公里默认都增加3%

                    distance = Convert.ToDecimal(Convert.ToDouble(rs.routes[0].distance) / 1000 * (1 - 0.03));

                    distance = Convert.ToDecimal(distance.ToString("0.0"));

                    //HJlog.toLog("接口距离:" + rs.routes[0].distance+"\r\n加3%:"+distance);
                }
            }

            /**************解析完成***************/


            return distance;
        }

        /// <summary>
        /// 获取直线距离(-1 表示未定位)
        /// </summary>
        /// <returns></returns>
        public decimal getLinDistance()
        {
            if (_slat == "" || _elat == "")
            {
                return -1;
            }
            double PI = 3.14159265358979323; // 圆周率
            double R = 6371; // 地球的半径
            double x, y;
            double lat1 = Convert.ToDouble(_slat);
            double longt1 = Convert.ToDouble(_slng);
            double lat2 = Convert.ToDouble(_elat);
            double longt2 = Convert.ToDouble(_elng);
            x = (longt2 - longt1) * PI * R * Math.Cos(((lat1 + lat2) / 2) * PI / 180) / 180;
            y = (lat2 - lat1) * PI * R / 180;
            return Convert.ToDecimal(Math.Sqrt(x * x + y * y)); ;
        }

        /// <summary>
        /// 访问服务端,获取信息
        /// </summary>
        /// <returns></returns>
        private BaiduMapInfo accessBaiduServer()
        {
            BaiduMapInfo mapdata = new BaiduMapInfo();

            // string url = "http://api.map.baidu.com/direction/v1?mode=driving&origin=" + _slat + "," + _slng + "&destination=" + _elat + "," + _elng + "&origin_region=" + cityname + "&destination_region=" + cityname + "&output=json&ak=nZk9ESfQoqhtuWhlyCdwF9c64jIaUjbX&tactics=12"; //w4GOVMIBQl2Hg2QD83vC2bpYwcl2PrLV  //nZk9ESfQoqhtuWhlyCdwF9c64jIaUjbX

            //以商家为起点。
            //string url = "http://api.map.baidu.com/direction/v1?mode=driving&destination=" + _slat + "," + _slng + "&origin=" + _elat + "," + _elng + "&origin_region=" + cityname + "&destination_region=" + cityname + "&output=json&ak=nZk9ESfQoqhtuWhlyCdwF9c64jIaUjbX&tactics=12"; //w4GOVMIBQl2Hg2QD83vC2bpYwcl2PrLV  //nZk9ESfQoqhtuWhlyCdwF9c64jIaUjbX

            //string url = "http://api.map.baidu.com/direction/v2/driving?&destination=" + _slat + "," + _slng + "&origin=" + _elat + "," + _elng + "&output=json&ak=U8IAr2sXderMwgk2IRC2RBObeaT3I0TL"; //w4GOVMIBQl2Hg2QD83vC2bpYwcl2PrLV  //nZk9ESfQoqhtuWhlyCdwF9c64jIaUjbX

            string url = "http://api.map.baidu.com/direction/v2/riding?&destination=" + _slat + "," + _slng + "&origin=" + _elat + "," + _elng + "&output=json&ak=U8IAr2sXderMwgk2IRC2RBObeaT3I0TL"; //w4GOVMIBQl2Hg2QD83vC2bpYwcl2PrLV  //nZk9ESfQoqhtuWhlyCdwF9c64jIaUjbX


            HttpHelper objhttp = new HttpHelper();
            objhttp.isToLower = false;
            HttpItem objHttpItem = new HttpItem()
            {
                URL = url,
                Encoding = "utf-8",
                Method = "GET",
            };
            string returnmsg = objhttp.GetHtml(objHttpItem);

            if (returnmsg == objhttp.ErrorCode)
            {
                mapdata = new BaiduMapInfo();
                mapdata.status = "-1";
            }
            else
            {
                mapdata = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<BaiduMapInfo>(returnmsg);
            }

            //Hangjing.AppLog.AppLog.Info(url + "\r\n获取驾车返回json:" + returnmsg);


            return mapdata;
        }


        /// <summary>
        /// 访问服务端,获取信息
        /// </summary>
        /// <returns></returns>
        public string compare()
        {
            string driving = "0";
            {
                BaiduMapInfo mapdata = new BaiduMapInfo();
                //以商家为起点。
                string url = "http://api.map.baidu.com/direction/v1?mode=driving&destination=" + _slat + "," + _slng + "&origin=" + _elat + "," + _elng + "&origin_region=" + cityname + "&destination_region=" + cityname + "&output=json&ak=nZk9ESfQoqhtuWhlyCdwF9c64jIaUjbX&tactics=12"; //w4GOVMIBQl2Hg2QD83vC2bpYwcl2PrLV  //nZk9ESfQoqhtuWhlyCdwF9c64jIaUjbX

                HttpHelper objhttp = new HttpHelper();
                objhttp.isToLower = false;
                HttpItem objHttpItem = new HttpItem()
                {
                    URL = url,
                    Encoding = "utf-8",
                    Method = "GET",
                };
                string returnmsg = objhttp.GetHtml(objHttpItem);

                if (returnmsg == objhttp.ErrorCode)
                {
                    mapdata = new BaiduMapInfo();
                    mapdata.status = "-1";
                }
                else
                {
                    mapdata = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<BaiduMapInfo>(returnmsg);



                    string jsonstr = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(mapdata.result);
                    BaiduResults rs = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<BaiduResults>(jsonstr);
                    if (rs != null && rs.routes != null & rs.routes.Count > 0)
                    {
                        driving = (Convert.ToDecimal(rs.routes[0].distance) / 100).ToString("0.0");

                    }

                }


            }

            string walking = "0";

            {
                BaiduMapInfo mapdata = new BaiduMapInfo();
                //以商家为起点。
                string url = "http://api.map.baidu.com/direction/v1?mode=walking&destination=" + _slat + "," + _slng + "&origin=" + _elat + "," + _elng + "&origin_region=" + cityname + "&destination_region=" + cityname + "&output=json&ak=nZk9ESfQoqhtuWhlyCdwF9c64jIaUjbX&tactics=12"; //w4GOVMIBQl2Hg2QD83vC2bpYwcl2PrLV  //nZk9ESfQoqhtuWhlyCdwF9c64jIaUjbX

                HttpHelper objhttp = new HttpHelper();
                objhttp.isToLower = false;
                HttpItem objHttpItem = new HttpItem()
                {
                    URL = url,
                    Encoding = "utf-8",
                    Method = "GET",
                };
                string returnmsg = objhttp.GetHtml(objHttpItem);

                if (returnmsg == objhttp.ErrorCode)
                {
                    mapdata = new BaiduMapInfo();
                    mapdata.status = "-1";
                }
                else
                {
                    mapdata = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<BaiduMapInfo>(returnmsg);


                    string jsonstr = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(mapdata.result);
                    BaiduResults rs = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<BaiduResults>(jsonstr);
                    if (rs != null && rs.routes != null & rs.routes.Count > 0)
                    {
                        walking = (Convert.ToDecimal(rs.routes[0].distance) / 100).ToString("0.0"); ;

                    }
                }


            }

            Hangjing.AppLog.AppLog.Debug(driving + "," + walking);


            return driving + "," + walking;
        }







        /// <summary>
        /// 坐标转换
        /// </summary>
        /// <returns></returns>
        public HttpItem convertLoacation()
        {
            string url = "http://api.map.baidu.com/geoconv/v1/?coords=" + _slng + "," + _slat + "&ak=nZk9ESfQoqhtuWhlyCdwF9c64jIaUjbX";

            HttpItem objHttpItem = new HttpItem()
            {
                URL = url,
                Encoding = "utf-8",
                Method = "GET",
            };


            return objHttpItem;

            //Hangjing.AppLog.AppLog.Debug(url + "坐标转换返回json:" + returnmsg);

        }

        /// <summary>
        /// 返回latlng
        /// </summary>
        /// <param name="httpdata"></param>
        /// <returns></returns>
        public string[] getBaiDuLatLng()
        {
            string[] bdlatlng = Hangjing.Common.HjNetHelper.bd_encrypt(Convert.ToDouble(_slat), Convert.ToDouble(_slng));

            string[] latlng = new string[] { bdlatlng[0], bdlatlng[1] };

            try
            {
                HttpHelper objhttp = new HttpHelper();


                string url = "http://api.map.baidu.com/geoconv/v1/?coords=" + _slng + "," + _slat + "&ak=nZk9ESfQoqhtuWhlyCdwF9c64jIaUjbX&from=3";

                HttpItem objHttpItem = new HttpItem()
                {
                    URL = url,
                    Encoding = "utf-8",
                    Method = "GET",
                };


                string returnmsg = objhttp.GetHtml(objHttpItem);
                if (returnmsg == objhttp.ErrorCode)
                {

                }
                else
                {
                    BaiduMapInfo mapdata = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<BaiduMapInfo>(returnmsg);
                    if (mapdata.status == "0")
                    {
                        string jsonstr = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(mapdata.result);
                        IList<LocationInfo> rs = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<IList<LocationInfo>>(jsonstr);
                        if (rs != null & rs.Count > 0)
                        {

                            latlng[0] = rs[0].y;
                            latlng[1] = rs[0].x;

                        }
                    }

                }

            }
            catch (Exception ex)
            {
                Hangjing.AppLog.AppLog.Error("转换失败：" + ex);
            }

       
            return latlng;
        }


    }
}
